package com.bluefuture.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bluefuture.modules.sys.security.TokenGenerator;
import com.bluefuture.modules.sys.service.SysUserTokenService;
import com.bluefuture.common.utils.R;
import com.bluefuture.modules.sys.dao.SysUserTokenDao;
import com.bluefuture.modules.sys.entity.SysUserTokenEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;


@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
	//七天后过期
	private final static int EXPIRE = 3600 * 24 * 180;


	@Override
	public R createToken(Integer platformType,long userId,String username) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//当前时间
		LocalDateTime now = LocalDateTime.now();
		//过期时间
		LocalDateTime expireTime = now.plusDays(180);

		//判断是否生成过token
		SysUserTokenEntity tokenEntity = this.getById(userId);
		if(tokenEntity == null){
			tokenEntity = new SysUserTokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
            tokenEntity.setUsername(username);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
//			if (Objects.nonNull(platformType)){
//				tokenEntity.setPlatformType(platformType);
//			}
			//保存token
			this.save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			this.updateById(tokenEntity);
		}

		R r = R.ok().put("token", token).put("expire", EXPIRE);

		return r;
	}

	@Override
	public void logout(long userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//修改token
		SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		this.updateById(tokenEntity);
	}
}
